//
//  ViewController.m
//  HTML_CSS_JS
//
//  Created by fans on 15/11/29.
//  Copyright © 2015年 FF. All rights reserved.
//

#import "ViewController.h"
#import "JSWebViewController.h"
#import "WKWebViewController.h"

@interface ViewController ()<UIWebViewDelegate, TestJSExport>

@end

@implementation ViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"vc";

    self.webView.delegate = self;
    NSURL * baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    NSString * path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString * html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:html baseURL:baseUrl];// web View 加载本地文件

// ************** web ***************
//    NSURL * webURL = [NSURL URLWithString:@"http://localhost/www/"];
//    NSURLRequest * request  =[NSURLRequest requestWithURL:webURL];
//    [self.webView loadRequest:request];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview :btn];
    btn.frame = CGRectMake(0,500,50,50);
    [btn setTitle:@"push" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pushVC:) forControlEvents:UIControlEventTouchUpInside ];
}
- (void)pushVC:(NSString *)view{
     WKWebViewController *nextVC = [[WKWebViewController alloc] init];
    [self.navigationController pushViewController:nextVC animated:YES];

}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"web request start!");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"finished!");

    self.jsContent = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 打印异常
    self.jsContent.exceptionHandler = ^(JSContext *context, JSValue *exception){
        context.exception = exception;
        NSLog(@"%@",exception);
    };

    // 以 JSExport 协议关联 native 的方法
    self.jsContent[@"native"] = self;
    self.jsContent[@"mutiParams"] = ^(NSString* name,NSNumber * num,NSString* string){
        NSLog(@"%@ %@ %@",name,num, string);
        
    };

    __weak typeof(self) weakSelf = self;
    self.jsContent[@"addView"] = ^(NSString* string){

        dispatch_async(dispatch_get_main_queue(), ^{
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
            view.backgroundColor = [UIColor purpleColor];
            [weakSelf.view addSubview:view];
        });

    };
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"did faild with error\n%@!",error);
}

// 异步操作 JS调用OC代码
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    NSURL * url = [request URL];
    if ([[url scheme] isEqualToString:@"devzeng"])  {
         //处理JavaScript和Objective-C交互
        if ([[url host] isEqualToString:@"login"]) {
            NSDictionary * parameters = [self getPramas:[url query]];
            BOOL status = [self login:[parameters objectForKey:@"name"] password:[parameters objectForKey:@"password"]];
            if (status) {
                //调用JS回调
                // 同步操作 OC调用JS代码
                [self.webView stringByEvaluatingJavaScriptFromString:@"confirm('登录成功')"];
            }else{
                [self.webView stringByEvaluatingJavaScriptFromString:@"alert('登录失败')"];
            }
        }
        
        [self normalJSMothed:webView];
        return NO;
    }
    return YES;
}
- (void)normalJSMothed:(UIWebView *)webView{
// 获取页面title
    NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"web view title is ==>%@",title);
    self.title = title;

    NSString * url = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSLog(@"the web view url is ==> %@",url);
}

/// 参数解析
- (NSDictionary*)getPramas:(NSString*)dic{
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"&"];
    NSMutableDictionary *mdic = [[NSMutableDictionary alloc] init];
    NSScanner *scanner = [NSScanner scannerWithString:dic];
    
    while (![scanner isAtEnd]) {
        NSString *pairstr = nil;
        [scanner scanUpToCharactersFromSet:set intoString:&pairstr];//从集合中扫描字符
        [scanner scanCharactersFromSet:set intoString:NULL];//扫描字符集
        NSArray *kvPair = [pairstr componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString *key = [[kvPair objectAtIndex:0] stringByRemovingPercentEncoding];
            NSString *value = [[kvPair objectAtIndex:1] stringByRemovingPercentEncoding];
            [mdic setObject:value forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:mdic];
}

/**
 登录校验

 @param name username
 @param password pwd
 @return result
 */
- (BOOL)login:(NSString*)name password:(NSString *)password{
    if ([name isEqualToString:@"jinlong"] && [password isEqualToString:@"000000"]) {
        return true;
    }else{
        return false;
    }
}

#pragma mark - TestJSExport protocol
- (int)jsCallOCFuntion:(NSNumber*)value{
    NSLog(@"%s %@",__func__,value);
    return value.intValue+1;
}

/// 实现js代用的方法
/// @param view js中传入的Controller
/// @param title js中传入的title
- (void)pushViewController:(NSString *)view title:(NSString *)title{
    NSLog(@"push view controller");
    
    dispatch_async(dispatch_get_main_queue(), ^{ //必须在主线程中push，默认是在其他线程
        Class next = NSClassFromString(view);
        id nextVC = [[next alloc]init];
        ((UIViewController*)nextVC).title = title;
//        JSWebViewController *nextVC = [[JSWebViewController alloc] initWithNibName:@"JSWebViewController" bundle:nil];
        [self.navigationController pushViewController:nextVC animated:YES];
    });
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)runAction:(id)sender {
    //oc -> js oc调js方法
    static int number = 0;
    JSValue * funcName = [self.jsContent objectForKeyedSubscript:@"log"];
    NSString *msg = [NSString stringWithFormat:@"msg %d",number];
    [funcName callWithArguments:@[@"data",msg]];
    number ++;
}
@end
